const modal = new bootstrap.Modal(document.querySelector("#modal"));
const openModal = document.querySelector("#openModal");
const total = document.querySelector(".total");
const list = document.querySelector(".list");
const form = document.querySelector("#form");
const submit = document.querySelector("#submit");

render()
// 页面渲染
async function render() {
    const res = await axios({
        url: "/students",
        method: "get"
    });

    total.innerText = res.data.data.length;
    let str = ''
    res.data.data.forEach(element => {
        const { id, name, age, gender, group, hope_salary, salary, province, city, area } = element;
        str += `
        <tr>
        <td>${name}</td>
        <td>${age}</td>
        <td>${gender === 0 ? '男' : '女'}</td>
        <td>${group}</td>
        <td>${hope_salary}</td>
        <td>${salary}</td>
        <td>${province + city + area}</td>
        <td>
          <a href="javascript:;" class="text-success mr-3"><i data-id="${id}" class="bi bi-pen"></i></a>
          <a href="javascript:;" class="text-danger"><i data-id="${id}" class="bi bi-trash"></i></a>
        </td>
        </tr>`
    });
    list.innerHTML = str;
}

// 添加学员
openModal.addEventListener("click", function () {
    modal.show();
    document.querySelector(".modal-title").innerText = "添加学员";
    getData()
    form.reset()
})


// 修改学院信息
list.addEventListener("click", async function (e) {
    id = e.target.dataset.id;
    if (e.target.classList.contains('bi-pen')) {
        modal.show();
        document.querySelector(".modal-title").innerText = "修改学员";

        const res = await axios({
            url: `/students/${id}`,
            method: "get"
        });
        const obj = res.data.data;

        let pname = obj.province
        let cname = obj.city
        await getSelectData('/api/city', { pname }, 'city')
        await getSelectData('/api/area', { pname, cname }, 'area')
        for (const key in res.data.data) {
            const formEle = form.querySelector(`[name=${key}]`)
            if (formEle && key != "gender") {
                formEle.value = obj[key]
            }

            obj.gender === 0 ? form.querySelector("#cb01").checked = true : form.querySelector("#cb02").checked = true
        }

    }
    // 删除学员功能
    else if (e.target.classList.contains('bi-trash')) {
        const res = await axios({
            url: `/students/${id}`,
            method: 'DELETE'
        });
        console.log(res);
        alert("你确定要删除？")
        document.querySelector('#myToast .toast-body').innerHTML = "删除成功";

        myToast.show()


        render()

    }
});

// 提交事件
submit.addEventListener("click", async function (e) {
    if (document.querySelector(".modal-title").innerText === '添加学员') {
        const data = serialize(document.querySelector('#form'), {
            hash: true
        })

        for (const key in data) {
            // 判断 是否为数字-->转换
            // isNaN 不是数字-->true 是数字(字符串)-->false

            if (isNaN(data[key]) === false) {
                // 需要转换
                data[key] = +data[key]
                if (key === "name") {
                    data[key] = data[key].toString()
                }
            }
        }
        const res = await axios({
            url: '/students',
            method: 'post',
            data
        })
        modal.hide();
        document.querySelector('#myToast .toast-body').innerHTML = res.data.message;
        myToast.show();
        render()
    } else if (document.querySelector(".modal-title").innerText === '修改学员') {
        const data = serialize(document.querySelector('#form'), {
            hash: true
        });
        for (const key in data) {
            // 判断 是否为数字-->转换
            // isNaN 不是数字-->true 是数字(字符串)-->false

            if (isNaN(data[key]) === false) {
                // 需要转换
                data[key] = +data[key]
                if (key === "name") {
                    data[key] = data[key].toString()
                }
            }
        }

        const res = await axios({
            url: `/students/${id}`,
            method: 'put',
            data
        })
        modal.hide();
        document.querySelector('#myToast .toast-body').innerHTML = res.data.message;
        myToast.show();
        form.reset();
        render()
    }
});
// 优化
async function getSelectData(url, params, target) {
    const res = await axios({
        url,
        params
    });
    const html = res.data.data.reduce((beforeHTML, item) => {
        return beforeHTML + `<option value="${item}">${item}</option>`
    }, '');
    document.querySelector(`[name=${target}]`).innerHTML = html;
}
// 获取省
async function getProvince() {
    await getSelectData('/api/province', {}, 'province')
}
// 获取市
async function getCity() {
    const pname = document.querySelector('[name=province]').value;
    console.log(pname);
    await getSelectData('/api/city', { pname }, 'city')
}

// 获取县
async function getArea() {
    const pname = document.querySelector('[name=province]').value;
    const cname = document.querySelector('[name=city]').value;
    await getSelectData('/api/area', { pname, cname }, 'area')
}

async function getData() {
    await getProvince();
    await getCity();
    await getArea()
}
getData()

// 点击省切换对应市
document.querySelector('[name=province]').addEventListener("change", async function (e) {
    await getCity();
    getArea()

})
// 点击市切换对应县
document.querySelector('[name=city]').addEventListener("change", async function (e) {
    getArea()
})



